package com.wenbai.servicelightluxurystickers.controller;

import com.wenbai.servicelightluxurystickers.utils.Response;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/upload")
public class UploadController {
    @PostMapping("/image")
    public ResponseEntity<Response> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body(Response.error("文件为空"));
        }
        try {
            String uploadDir = new ClassPathResource("static/").getFile().getAbsolutePath() ;
            File imgDir = new File(uploadDir);
            if (!imgDir.exists()) {
                imgDir.mkdirs();
            }
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename().replace(" ", "_");
            File dest = new File(uploadDir + "/" + fileName);
            file.transferTo(dest);
            return ResponseEntity.ok(Response.success("上传成功", fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(Response.error("上传失败"));
        }
    }
}
